'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Loader2 } from 'lucide-react'
import ReactECharts from 'echarts-for-react'

interface HeartRateData {
  timestamp: number
  value: number
  type?: 'auto' | 'manual'
}

interface RestingHeartRateData {
  timestamp: number
  value: number
}

interface HeartRateChartProps {
  userId: string
  selectedDate: string
}

export function HeartRateChart({ userId, selectedDate }: HeartRateChartProps) {
  const [chartType, setChartType] = useState<'resting' | 'realtime'>('resting')
  const [heartRateData, setHeartRateData] = useState<HeartRateData[]>([])
  const [restingHeartRateData, setRestingHeartRateData] = useState<RestingHeartRateData[]>([])
  const [loading, setLoading] = useState(false)

  // 获取实时心率数据
  const fetchRealTimeHeartRateData = async () => {
    try {
      // 数据库中的时间戳是本地时间戳，直接构造本地时间范围
      const selectedDateObj = new Date(selectedDate)
      
      // 构造本地时间的开始和结束时间戳
      const startDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate(), 0, 0, 0, 0)
      const endDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate() + 1, 0, 0, 0, 0)
      
      console.log('实时心率查询时间范围:', {
        selectedDate,
        startDate: startDate.toLocaleString('zh-CN'),
        endDate: endDate.toLocaleString('zh-CN'),
        startDateISO: startDate.toISOString(),
        endDateISO: endDate.toISOString(),
        startTimestamp: startDate.getTime(),
        endTimestamp: endDate.getTime()
      })

      const response = await fetch(`/api/health?userId=${userId}&dataType=heart_rate&startDate=${startDate.toISOString()}&endDate=${endDate.toISOString()}`)
      
      if (!response.ok) {
        throw new Error('Failed to fetch heart rate data')
      }

      const data = await response.json()
      // console.log('实时心率 API响应:', data)
      // console.log('实时心率 API响应结构检查:', {
      //   hasData: !!data.data,
      //   hasLogs: !!data.data?.logs,
      //   logsLength: data.data?.logs?.length || 0,
      //   directLogsLength: data.logs?.length || 0,
      //   dataStructure: Object.keys(data)
      // })

      // 修复数据路径：API返回的是 data.data.logs，不是 data.logs
      const logs = data.data?.logs || data.logs || []
      // console.log('实时心率 提取的logs:', {
      //   logsLength: logs.length,
      //   firstLog: logs[0] || null,
      //   lastLog: logs[logs.length - 1] || null
      // })

      const processedData = processRealTimeHeartRateData(logs)
      console.log('处理后的实时心率数据:', {
        originalLogsCount: logs.length,
        processedDataCount: processedData.length,
        firstProcessedData: processedData[0] ? {
          timestamp: processedData[0].timestamp,
          timestampDate: new Date(processedData[0].timestamp).toISOString(),
          timestampLocal: new Date(processedData[0].timestamp).toLocaleString('zh-CN'),
          hour: new Date(processedData[0].timestamp).getHours(),
          value: processedData[0].value,
          type: processedData[0].type
        } : null,
        lastProcessedData: processedData[processedData.length - 1] ? {
          timestamp: processedData[processedData.length - 1].timestamp,
          timestampDate: new Date(processedData[processedData.length - 1].timestamp).toISOString(),
          timestampLocal: new Date(processedData[processedData.length - 1].timestamp).toLocaleString('zh-CN'),
          hour: new Date(processedData[processedData.length - 1].timestamp).getHours(),
          value: processedData[processedData.length - 1].value,
          type: processedData[processedData.length - 1].type
        } : null
      })
      setHeartRateData(processedData)
    } catch (error) {
      console.error('获取实时心率数据失败:', error) // 保留错误日志
      setHeartRateData([])
    }
  }

  // 获取静息心率数据
  const fetchRestingHeartRateData = async () => {
    try {
      // 数据库中的时间戳是本地时间戳，直接构造本地时间范围
      const selectedDateObj = new Date(selectedDate)
      
      // 构造本地时间的开始和结束时间戳
      const startDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate(), 0, 0, 0, 0)
      const endDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate() + 1, 0, 0, 0, 0)

      // 获取睡眠数据
      const sleepResponse = await fetch(`/api/health?userId=${userId}&dataType=sleep&startDate=${startDate.toISOString()}&endDate=${endDate.toISOString()}`)
      const sleepData = await sleepResponse.json()

      // 获取心率数据
      const heartRateResponse = await fetch(`/api/health?userId=${userId}&dataType=heart_rate&startDate=${startDate.toISOString()}&endDate=${endDate.toISOString()}`)
      const heartRateData = await heartRateResponse.json()

      const restingData = calculateRestingHeartRate(sleepData.data.logs || [], heartRateData.data.logs || [])
      setRestingHeartRateData(restingData)
    } catch (error) {
      console.error('获取静息心率数据失败:', error) // 保留错误日志
      setRestingHeartRateData([])
    }
  }

  // 处理实时心率数据
  const processRealTimeHeartRateData = (logs: any[]): HeartRateData[] => {
    const heartRatePoints: HeartRateData[] = []
    logs.forEach((log, logIndex) => {
      const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data

      if (logData.onceHeartValue) {
        
        // 处理时间戳：优先使用logData中的ts，如果没有则使用log的timestamp
        let timestamp = parseInt(logData.ts) || parseInt(log.timestamp)
        
        // 如果时间戳是10位（秒级），转换为13位（毫秒级）
        if (timestamp < 10000000000) {
          timestamp = timestamp * 1000
        }
        
        // 检查时间戳是否在合理范围内（2020-2070年之间，适应未来时间戳）
        const minValidTimestamp = new Date('2020-01-01').getTime()
        const maxValidTimestamp = new Date('2070-12-31').getTime()
        
        if (timestamp < minValidTimestamp || timestamp > maxValidTimestamp) {
          console.warn('跳过无效时间戳:', {
            originalTimestamp: logData.ts || log.timestamp,
            convertedTimestamp: timestamp,
            timestampDate: new Date(timestamp).toISOString()
          })
          return // 跳过这个无效的时间戳（在forEach中跳过当前迭代）
        }
        
        const heartRateValue = parseInt(logData.onceHeartValue)
        
        heartRatePoints.push({
          timestamp,
          value: heartRateValue,
          type: logData.isAutoMeasure === false ? 'manual' : 'auto'
        })
        
      } else {

      }
      
      if (logData.arrayHeartValue && Array.isArray(logData.arrayHeartValue)) {
        
        let baseTimestamp = parseInt(logData.ts) || parseInt(log.timestamp)
        
        // 如果时间戳是10位（秒级），转换为13位（毫秒级）
        if (baseTimestamp < 10000000000) {
          baseTimestamp = baseTimestamp * 1000
        }
        
        logData.arrayHeartValue.forEach((heartRate: number, index: number) => {
          if (heartRate > 0) {
            const timestamp = baseTimestamp + (index * 60000) // 每分钟一个数据点
            heartRatePoints.push({
              timestamp,
              value: heartRate,
              type: 'auto'
            })
          }
        })
      }
    })

    return heartRatePoints.sort((a, b) => a.timestamp - b.timestamp)
  }

  // 计算静息心率
  const calculateRestingHeartRate = (sleepLogs: any[], heartRateLogs: any[]): RestingHeartRateData[] => {

    // 提取睡眠期间
    const sleepPeriods: Array<{ start: number; end: number; type: string }> = []

    sleepLogs.forEach((log, logIndex) => {
      const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data

      if (logData.arraySleepQuality && Array.isArray(logData.arraySleepQuality)) {
        const sleepData = logData.arraySleepQuality
        let currentBaseTimestamp = parseInt(logData.startTs || log.timestamp)
        // 确保 baseTimestamp 是毫秒级
        if (currentBaseTimestamp < 10000000000) {
          currentBaseTimestamp *= 1000
        }

        let consecutiveSleepMinutes = 0
        let currentSleepPeriodStart = -1

        for (let i = 0; i < sleepData.length; i++) {
          const quality = sleepData[i]
          const isDeepOrLightSleep = (quality === 1 || quality === 2) // 1: 深度睡眠, 2: 浅睡眠

          if (isDeepOrLightSleep) {
            if (consecutiveSleepMinutes === 0) {
              // 开始一个新的连续睡眠时段
              currentSleepPeriodStart = currentBaseTimestamp + (i * 60000)
            }
            consecutiveSleepMinutes++
          } else {
            // 睡眠中断，检查前一个连续睡眠时段是否符合10分钟要求
            if (consecutiveSleepMinutes >= 10) {
              const periodEnd = currentSleepPeriodStart + (consecutiveSleepMinutes * 60000)
              sleepPeriods.push({
                start: currentSleepPeriodStart,
                end: periodEnd,
                type: '深/浅睡眠' // 统一类型
              })
            }
            consecutiveSleepMinutes = 0 // 重置计数器
            currentSleepPeriodStart = -1 // 重置起始时间
          }
        }

        // 循环结束后，检查最后一个连续睡眠时段
        if (consecutiveSleepMinutes >= 10) {
          const periodEnd = currentSleepPeriodStart + (consecutiveSleepMinutes * 60000)
          sleepPeriods.push({
            start: currentSleepPeriodStart,
            end: periodEnd,
            type: '深/浅睡眠'
          })
        }
      }
    })

    // 提取睡眠期间的心率数据
    const sleepHeartRateData: HeartRateData[] = []

    heartRateLogs.forEach((log, logIndex) => {
      const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data

      if (logData.onceHeartValue) {
        let timestamp = parseInt(logData.ts || log.timestamp)
        // 确保时间戳是毫秒级
        if (timestamp < 10000000000) {
          timestamp *= 1000
        }
        
        const heartRateValue = parseInt(logData.onceHeartValue)

        // 添加心率值合理性检查
        if (isNaN(heartRateValue) || heartRateValue <= 0 || heartRateValue > 300) {
          console.warn(`静息心率 跳过不合理的心率单次值:`, {
            logId: log.id,
            timestamp: new Date(timestamp).toLocaleString(),
            originalValue: logData.onceHeartValue,
            parsedValue: heartRateValue
          }) // 保留警告日志
          // 如果值不合理，则跳过此数据点
        } else { // 确保心率值合理的情况下才继续处理
          // 检查是否在睡眠期间
          const matchingSleepPeriod = sleepPeriods.find(period => 
            timestamp >= period.start && timestamp < period.end
          )
          
          if (matchingSleepPeriod) {
            sleepHeartRateData.push({
              timestamp,
              value: heartRateValue,
              type: logData.measurementType === 1 ? 'auto' : 'manual'
            })
          }
        }
      }

      if (logData.arrayHeartValue && Array.isArray(logData.arrayHeartValue)) {
        let baseTimestamp = parseInt(logData.ts || log.timestamp)
        // 确保时间戳是毫秒级
        if (baseTimestamp < 10000000000) {
          baseTimestamp *= 1000
        }

        logData.arrayHeartValue.forEach((heartRate: number, index: number) => {
          // 添加心率值合理性检查
          if (isNaN(heartRate) || heartRate <= 0 || heartRate > 300) {
            console.warn(`静息心率 跳过不合理的心率数组值:`, {
              logId: log.id,
              index: index,
              timestamp: new Date(baseTimestamp + (index * 60000)).toLocaleString(),
              originalValue: heartRate
            }) // 保留警告日志
            return // 跳过此不合理的心率数据点
          }

          if (heartRate > 0) { // 保持原始的 heartRate > 0 检查，但在前面增加了更严格的检查
            const timestamp = baseTimestamp + (index * 60000)
            
            // 检查是否在睡眠期间
            const matchingSleepPeriod = sleepPeriods.find(period => 
              timestamp >= period.start && timestamp < period.end
            )
            
            if (matchingSleepPeriod) {
              sleepHeartRateData.push({
                timestamp,
                value: heartRate,
                type: 'auto'
              })
            }
          }
        })
      }
    })

    // 使用滑动窗口计算静息心率
    const restingHeartRateData = calculateRestingHeartRateWindows(sleepHeartRateData)

    return restingHeartRateData
  }

  // 滑动窗口计算静息心率
  const calculateRestingHeartRateWindows = (heartRateData: HeartRateData[]): RestingHeartRateData[] => {

    if (heartRateData.length === 0) {
      return []
    }

    // 按时间排序
    const sortedData = heartRateData.sort((a, b) => a.timestamp - b.timestamp)
    const windowSizeMinutes = 30 // 30分钟窗口
    const stepSizeMinutes = 30    // 30分钟步长
    const windowSizeMs = windowSizeMinutes * 60 * 1000
    const stepSizeMs = stepSizeMinutes * 60 * 1000

    const startTime = sortedData[0].timestamp
    const endTime = sortedData[sortedData.length - 1].timestamp

    const restingHeartRateData: RestingHeartRateData[] = []
    let validWindows = 0
    let totalWindows = 0

    // 如果数据时间跨度小于窗口大小，直接计算整体平均值
    if (endTime - startTime < windowSizeMs) {
      const avgHeartRate = Math.round(sortedData.reduce((sum, d) => sum + d.value, 0) / sortedData.length) // 计算平均心率
      const avgTimestamp = startTime + (endTime - startTime) / 2
      
      restingHeartRateData.push({
        timestamp: avgTimestamp,
        value: avgHeartRate // 使用平均心率
      })
      
      return restingHeartRateData
    }

    for (let windowStart = startTime; windowStart <= endTime - windowSizeMs; windowStart += stepSizeMs) {
      const windowEnd = windowStart + windowSizeMs
      totalWindows++

      // 获取窗口内的数据
      const windowData = sortedData.filter(data => 
        data.timestamp >= windowStart && data.timestamp < windowEnd
      )

      if (windowData.length >= 1) { // 至少1个数据点
        // 计算窗口内的平均心率作为静息心率
        const avgHeartRate = Math.round(windowData.reduce((sum, d) => sum + d.value, 0) / windowData.length) // 计算平均心率
        const windowCenter = windowStart + windowSizeMs / 2

        restingHeartRateData.push({
          timestamp: windowCenter,
          value: avgHeartRate
        })
        
        validWindows++
        
      } else {

      }
    }
    return restingHeartRateData
  }

  // 生成实时心率图表配置
  const generateRealTimeHeartRateChart = () => {
    if (heartRateData.length === 0) return null

    // 按1小时聚合数据
    const hourlyData = new Map<string, { min: number; max: number; auto: number; manual: number; count: number }>()

    // 从实际数据中获取日期范围，如果有数据则使用数据的日期，否则使用selectedDate
    let dayStart: Date
    
    if (heartRateData.length > 0) {
      // 使用实际数据的第一个时间戳来确定日期（本地时间）
      const firstDataDate = new Date(heartRateData[0].timestamp)
      dayStart = new Date(firstDataDate.getFullYear(), firstDataDate.getMonth(), firstDataDate.getDate())
    } else {
      // 如果没有数据，使用 selectedDate 的本地零点作为基准
      const selectedDateObj = new Date(selectedDate)
      dayStart = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate())
    }

    // 初始化24小时的数据结构
    for (let hour = 0; hour < 24; hour++) {
      // 使用本地时间方法创建小时开始时间
      const hourStart = new Date(dayStart.getFullYear(), dayStart.getMonth(), dayStart.getDate(), hour)
      const hourKey = `${hour.toString().padStart(2, '0')}:00` // 简化为小时标识符
      hourlyData.set(hourKey, { min: Infinity, max: -Infinity, auto: 0, manual: 0, count: 0 })
    }

    // 聚合心率数据到对应小时
    heartRateData.forEach(data => {
      const dataDate = new Date(data.timestamp)
      // 使用本地时间获取小时
      const hour = dataDate.getHours()
      const hourKey = `${hour.toString().padStart(2, '0')}:00`
      
      if (hourlyData.has(hourKey)) {
        const hourData = hourlyData.get(hourKey)!
        hourData.min = Math.min(hourData.min, data.value)
        hourData.max = Math.max(hourData.max, data.value)
        hourData.count++
        
        if (data.type === 'auto') {
          hourData.auto++
        } else {
          hourData.manual++
        }

      } else {

      }
    })

    // 计算全天心率的最小值和最大值
    const allValues = heartRateData.map(d => d.value)
    const globalMin = Math.min(...allValues)
    const globalMax = Math.max(...allValues)

    // 计算Y轴的动态刻度范围（整10值）
    const yAxisMin = Math.floor(globalMin / 10) * 10  // 向下取整到最近的10
    const yAxisMax = Math.ceil(globalMax / 10) * 10   // 向上取整到最近的10

    // 准备图表数据 - 生成完整的24小时数据，包括没有数据的小时
    const xAxisData: string[] = []
    const seriesData: any[] = []

    // 生成完整的24小时X轴标签
    for (let hour = 0; hour < 24; hour++) {
      const hourLabel = hour.toString().padStart(2, '0') + ':00'
      xAxisData.push(hourLabel)
      
      // 查找对应小时的数据（使用简化的hourKey）
      const hourKey = `${hour.toString().padStart(2, '0')}:00`
      const hourData = hourlyData.get(hourKey)
      
      if (hourData && hourData.count > 0) {
        // 条形数据：[最小值, 最大值] - 用于自定义渲染
        seriesData.push({
          value: [hour, hourData.min, hourData.max],
          min: hourData.min,
          max: hourData.max,
          count: hourData.count
        })
      } else {
        // 没有数据的小时
        seriesData.push({
          value: [hour, 0, 0],
          min: 0,
          max: 0,
          count: 0
        })
      }
    }

    return {
      title: {
        text: '实时心率分析',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          if (params && params.length > 0) {
            const data = params[0]
            const hourLabel = data.name // 例如 "08:00"
            const itemData = data.data
            
            // 使用实际数据的日期而不是selectedDate，确保正确显示未来日期
            const [hour, minute] = hourLabel.split(':').map(Number)
            let displayDateTime: string
            
            if (heartRateData.length > 0) {
              // 使用实际数据的日期
              const firstDataDate = new Date(heartRateData[0].timestamp)
              const displayDate = new Date(firstDataDate.getFullYear(), firstDataDate.getMonth(), firstDataDate.getDate(), hour, minute, 0)
              displayDateTime = displayDate.toLocaleString('zh-CN', {
                year: 'numeric',
                month: 'numeric',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
              })
            } else {
              // 如果没有数据，使用selectedDate
              const selectedDateObj = new Date(selectedDate)
              const displayDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate(), hour, minute, 0)
              displayDateTime = displayDate.toLocaleString('zh-CN', {
                year: 'numeric',
                month: 'numeric',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
              })
            }

            if (itemData.count === 0) {
              return `${displayDateTime}<br/>无心率数据`
            }
            
            const rangeValue = itemData.max - itemData.min
            return `${displayDateTime}<br/>心率范围: ${itemData.min} - ${itemData.max} bpm<br/>范围差值: ${rangeValue} bpm<br/>测量次数: ${itemData.count}次`
          }
          return ''
        }
      },
      xAxis: {
        type: 'category',
        data: xAxisData,
        axisLabel: {
          interval: 1, // 每2小时显示一个刻度
          formatter: (value: string, index: number) => {
            return index % 2 === 0 ? value : '' // 只显示偶数索引的标签（00:00, 02:00, 04:00...）
          }
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        name: '心率 (bpm)',
        min: yAxisMin, // 动态最小值（整10值）
        max: yAxisMax, // 动态最大值（整10值）
        interval: 10,  // 每10个单位一个刻度
        axisLabel: {
          formatter: '{value}'
        }
      },
      series: [{
        name: '心率范围',
        type: 'custom',
        renderItem: (params: any, api: any) => {
          const categoryIndex = api.value(0)
          const minValue = api.value(1)
          const maxValue = api.value(2)
          
          if (minValue === 0 && maxValue === 0) {
            // 没有数据时不渲染
            return null
          }
          
          const start = api.coord([categoryIndex, minValue])
          const end = api.coord([categoryIndex, maxValue])
          const width = api.size([1, 0])[0] * 0.6 // 条形宽度
          
          return {
            type: 'rect',
            shape: {
              x: start[0] - width / 2,
              y: end[1],
              width: width,
              height: start[1] - end[1],
              r: 4 // 添加圆角半径，例如 4
            },
            style: {
              fill: '#ef4444', // 红色
              opacity: 0.8
            }
          }
        },
        data: seriesData
      }]
    }
  }

  // 生成静息心率图表配置
  const generateRestingHeartRateChart = () => {
    if (restingHeartRateData.length === 0) return null

    // 处理数据，在间隔大于1小时的点之间插入null值来断开曲线
    const processedSeriesData: (number[] | null)[] = []
    const sortedData = [...restingHeartRateData].sort((a, b) => a.timestamp - b.timestamp)
    
    for (let i = 0; i < sortedData.length; i++) {
      const currentData = sortedData[i]
      processedSeriesData.push([currentData.timestamp, currentData.value])
      
      // 检查与下一个数据点的时间间隔
      if (i < sortedData.length - 1) {
        const nextData = sortedData[i + 1]
        const timeDiff = nextData.timestamp - currentData.timestamp
        const oneHourInMs = 60 * 60 * 1000 // 1小时的毫秒数
        
        // 如果间隔大于1小时，插入null值来断开曲线
        if (timeDiff > oneHourInMs) {
          processedSeriesData.push(null)
        }
      }
    }

    return {
      title: {
        text: '静息心率趋势',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          if (params && params.length > 0 && params[0].value) {
            const data = params[0]
            const time = new Date(data.value[0]).toLocaleString('zh-CN')
            return `${time}<br/>静息心率: ${data.value[1]} bpm`
          }
          return ''
        }
      },
      xAxis: {
        type: 'time',
        axisLabel: {
          formatter: (value: number) => {
            return new Date(value).toLocaleTimeString('zh-CN', { 
              hour: '2-digit', minute: '2-digit' 
            })
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '心率 (bpm)',
        min: (value: any) => Math.max(40, value.min - 5),
        max: (value: any) => value.max + 5
      },
      series: [{
        name: '静息心率',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        connectNulls: false, // 关键配置：不连接null值，实现曲线断开
        lineStyle: {
          color: '#22c55e',
          width: 3
        },
        itemStyle: {
          color: '#22c55e'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(34, 197, 94, 0.3)' },
              { offset: 1, color: 'rgba(34, 197, 94, 0.1)' }
            ]
          }
        },
        data: processedSeriesData
      }]
    }
  }

  // 计算心率统计（平均值和标准差）
  const calculateHeartRateStatistics = (heartRates: number[]) => {
    if (heartRates.length === 0) {
      return { mean: 0, stdDev: 0, variance: 0 }
    }

    // 第一步：计算平均心率
    const hrMean = heartRates.reduce((sum, hr) => sum + hr, 0) / heartRates.length

    // 第二步：计算每个样本点与平均值的差的平方
    const squaredDiffs = heartRates.map(hr => {
      const diff = hr - hrMean
      return diff * diff
    })

    // 第三步：计算方差
    const variance = squaredDiffs.reduce((sum, diff) => sum + diff, 0) / squaredDiffs.length

    // 第四步：计算标准差
    const stdDev = Math.sqrt(variance)

    return {
      mean: Math.round(hrMean * 10) / 10, // 保留一位小数
      stdDev: Math.round(stdDev * 10) / 10, // 保留一位小数
      variance: Math.round(variance * 10) / 10 // 保留一位小数
    }
  }

  // 获取统计信息
  const getStatistics = () => {
    if (chartType === 'resting') {
      if (restingHeartRateData.length === 0) {
        return {
          title: '静息心率统计',
          stats: [
            { label: '数据点', value: '0' },
            { label: '平均静息心率', value: '无数据' },
            { label: '心率范围', value: '无数据' },
            { label: '数据说明', value: '基于睡眠期间心率计算' }
          ]
        }
      }

      const values = restingHeartRateData.map(d => d.value)
      // 计算所有窗口平均心率中的最低值作为当晚的静息心率
      const minAvgRestingHR = Math.min(...values) 
      const minRestingHR = Math.min(...values)
      const maxRestingHR = Math.max(...values)

      return {
        title: '静息心率统计',
        stats: [
          { label: '数据点', value: restingHeartRateData.length.toString() },
          { label: '平均静息心率', value: `${minAvgRestingHR} bpm` }, // 显示最低平均心率
          { label: '心率范围', value: `${minRestingHR} - ${maxRestingHR} bpm` },
          { label: '时间窗口', value: '10分钟' }
        ]
      }
    } else {
      if (heartRateData.length === 0) {
        return {
          title: '实时心率统计',
          stats: [
            { label: '总测量次数', value: '0' },
            { label: '平均心率', value: '无数据' },
            { label: '心率范围', value: '无数据' },
            { label: '心率标准差', value: '无数据' },
            { label: '自动测量', value: '0次' },
            { label: '手动测量', value: '0次' }
          ]
        }
      }

      const values = heartRateData.map(d => d.value)
      const minHR = Math.min(...values)
      const maxHR = Math.max(...values)
      const autoCount = heartRateData.filter(d => d.type === 'auto').length
      const manualCount = heartRateData.filter(d => d.type === 'manual').length
      
      // 计算心率统计
      const statistics = calculateHeartRateStatistics(values)

      return {
        title: '实时心率统计',
        stats: [
          { label: '总测量次数', value: heartRateData.length.toString() },
          { label: '平均心率', value: `${statistics.mean} bpm` },
          { label: '心率范围', value: `${minHR} - ${maxHR} bpm` },
          { label: '心率标准差', value: `±${statistics.stdDev} bpm` },
          { label: '自动测量', value: `${autoCount}次` },
          { label: '手动测量', value: `${manualCount}次` }
        ]
      }
    }
  }

  // 数据获取
  useEffect(() => {
    if (!userId || !selectedDate) return

    setLoading(true)
    
    const fetchData = async () => {
      if (chartType === 'resting') {
        await fetchRestingHeartRateData()
      } else {
        await fetchRealTimeHeartRateData()
      }
      setLoading(false)
    }

    fetchData()
  }, [userId, selectedDate, chartType])

  const statistics = getStatistics()
  const chartConfig = chartType === 'resting' ? generateRestingHeartRateChart() : generateRealTimeHeartRateChart()

  return (
    <div className="space-y-4">
      {/* 选项卡 */}
      <div className="flex space-x-2">
        <Button
          variant={chartType === 'resting' ? 'default' : 'outline'}
          onClick={() => setChartType('resting')}
          className={`px-4 py-2 rounded-md transition-all ${
            chartType === 'resting' 
              ? 'bg-white text-gray-900 shadow-md border border-gray-200' 
              : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
          }`}
        >
          静息心率
        </Button>
        <Button
          variant={chartType === 'realtime' ? 'default' : 'outline'}
          onClick={() => setChartType('realtime')}
          className={`px-4 py-2 rounded-md transition-all ${
            chartType === 'realtime' 
              ? 'bg-white text-gray-900 shadow-md border border-gray-200' 
              : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
          }`}
        >
          实时心率
        </Button>
      </div>

      {/* 图表区域 */}
      <Card>
        <CardHeader>
          <CardTitle>{chartType === 'resting' ? '静息心率分析' : '实时心率分析'}</CardTitle>
          <CardDescription>
            {chartType === 'resting' 
              ? '基于睡眠期间的心率数据，使用10分钟滑动窗口计算静息心率趋势' 
              : '显示全天的心率测量数据，按小时聚合显示心率范围'
            }
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center h-64">
              <Loader2 className="h-8 w-8 animate-spin" />
              <span className="ml-2">加载中...</span>
            </div>
          ) : chartConfig ? (
            <ReactECharts
              option={chartConfig}
              style={{ width: '100%', height: '400px' }}
              opts={{ renderer: 'canvas' }}
            />
          ) : (
            <div className="flex items-center justify-center h-64 text-gray-500">
              <div className="text-center">
                <p className="text-lg font-medium">暂无数据</p>
                <p className="text-sm">
                  {chartType === 'resting' 
                    ? '该日期没有睡眠期间的心率数据' 
                    : '该日期没有心率测量数据'
                  }
                </p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 统计信息 */}
      <Card>
        <CardHeader>
          <CardTitle>{statistics.title}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className={`grid gap-4 ${
            chartType === 'realtime' 
              ? 'grid-cols-2 md:grid-cols-3 lg:grid-cols-6' 
              : 'grid-cols-2 md:grid-cols-4'
          }`}>
            {statistics.stats.map((stat, index) => (
              <div key={index} className="text-center p-3 bg-gray-50 rounded-lg">
                <div className="text-xl font-bold text-gray-900">{stat.value}</div>
                <div className="text-xs text-gray-600">{stat.label}</div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  )
}